package comments

import (
	"encoding/json"
	"financial_manual_server/util"
	"io/ioutil"
	"log"
	"net/http"
)

// 获取评论列表
func ListComment(w http.ResponseWriter, r *http.Request) {
	id := util.GetStringParam(r, "id")
	comments, count := listComment(id)

	result := make(map[string]interface{}, 0)
	result["total"] = count
	result["comments"] = comments

	body, _ := util.Success(result)
	util.WriteJson(w, body)
}

// 增加评论
func AddComment(w http.ResponseWriter, r *http.Request) {
	body, _ := ioutil.ReadAll(r.Body)
	result, _ := jsonUnmarshal(body)
	comment := result.(CommentBody)

	// 根据用户ID 获取用户名称
	person := getUserNameById(comment.UserId)
	log.Println(person)
	if person != nil {
		comment.UserName = person.PersonName
	}

	count, err := addComment(comment)
	if err == nil && count > 0 {
		body, _ = util.Success(nil)
	} else {
		log.Println(err)
		body, _ = util.Fail("", err)
	}
	util.WriteJson(w, body)
}

// 删除评论
func DeleteComment(w http.ResponseWriter, r *http.Request) {
	id := util.GetStringParam(r, "id")
	var body []byte

	// 删除评论
	count, err := deleteComment(id)
	if err != nil {
		log.Println("Delete Comment Fail", err)
		body, _ = util.Fail("Delete Comment Fail", err)
	} else if count == 0 {
		body, _ = util.Fail("The comment does not exist or has been deleted", err)
	} else {
		body, _ = util.Success(nil)
	}
	util.WriteJson(w, body)
}

// 赞同评论
func Agree(w http.ResponseWriter, r *http.Request) {
	id, _ := util.GetIntParam(r, "id")
	var body []byte

	count, err := agreeComment(id)
	if err != nil {
		log.Println("Agree Comment Fail", err)
		body, _ = util.Fail("Agree Comment Fail", err)
	} else if count == 0 {
		body, _ = util.Fail("The comment does not exist or has been deleted", err)
	} else {
		body, _ = util.Success(nil)
	}
	util.WriteJson(w, body)
}

// 员工信息（通过接口获取）
type basePerson struct {
	PersonCode       string `json:"personCode"`
	PersonName       string `json:"personName"`
	DepartmentCode   string `json:"departmentCode"`
	OrganizationCode string `json:"organizationCode"`
	CompanyCode      string `json:"companyCode"`
}

// 根据用记工号获取用户信息
func getUserNameById(userId string) *basePerson {
	baseInfoApi := util.GetConfig().WxWork.BaseInfoApi
	personUrl := baseInfoApi + "commonUtil/person/" + userId
	resp, err := http.Get(personUrl)
	if err != nil {
		log.Println("Fail to get person info", err)
		return nil
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	var tempMap map[string]interface{}
	err = json.Unmarshal(body, &tempMap)
	if err != nil || int(tempMap["code"].(float64)) != 0 {
		log.Println("Fail to parse person info")
		return nil
	}

	var person basePerson
	body, err = json.Marshal(tempMap["data"])
	err = json.Unmarshal(body, &person)

	return &person
}
